﻿/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <cstring>
#include "Player.h"
#include "Util/logger.h"

using namespace ZL::Util;

static unsigned const samplingFrequencyTable[16] = { 96000, 88200,
					64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025,
					8000, 7350, 0, 0, 0 };


string 	makeAdtsConfig(const uint8_t *pcAdts){
	if (!(pcAdts[0] == 0xFF && (pcAdts[1] & 0xF0) == 0xF0)) {
		return "";
	}
	// Get and check the 'profile':
	unsigned char profile = (pcAdts[2] & 0xC0) >> 6; // 2 bits
	if (profile == 3) {
		return "";
	}

	// Get and check the 'sampling_frequency_index':
	unsigned char sampling_frequency_index = (pcAdts[2] & 0x3C) >> 2; // 4 bits
	if (samplingFrequencyTable[sampling_frequency_index] == 0) {
		return "";
	}

	// Get and check the 'channel_configuration':
	unsigned char channel_configuration = ((pcAdts[2] & 0x01) << 2)
			| ((pcAdts[3] & 0xC0) >> 6); // 3 bits

	unsigned char audioSpecificConfig[2];
	unsigned char const audioObjectType = profile + 1;
	audioSpecificConfig[0] = (audioObjectType << 3) | (sampling_frequency_index >> 1);
	audioSpecificConfig[1] = (sampling_frequency_index << 7) | (channel_configuration << 3);
	return string((char *)audioSpecificConfig,2);
}
